/**
 * Propriedade de Fastfind Tecnologia.
 */
package br.com.srv.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;

import br.com.srv.componentes.cerca.util.PontosTOComparator;
import br.com.srv.componentes.relatorio.pontoparada.service.PontoParadaService;
import br.com.srv.componentes.relatorio.posicoes.service.PosicoesService;
import br.com.srv.componentes.rota.service.RotaService;
import br.com.srv.model.PeriodoTO;
import br.com.srv.model.PontoTO;
import br.com.srv.model.RotaTO;
import br.com.srv.model.VeiculoTO;
import br.com.srv.security.SecurityPrincipal;
import br.com.srv.util.StringHelper;


public final class GoogleEarthAction extends BaseAction {
	
	public final String ROUTE_VEICULOS = "route_veiculos";

	public ActionForward point(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String[] desc = request.getParameterValues("DESC");
			String[] x = request.getParameterValues("X");
			String[] y = request.getParameterValues("Y");
			ArrayList pontos = new ArrayList(desc.length);
			for (int i = 0; i < desc.length; i++) {
				HashMap map = new HashMap(4);
				map.put("DESC", desc[i]);
				map.put("X", x[i]);
				map.put("Y", y[i]);
				map.put("DATE_TIME", "");
				pontos.add(map);
			}
			pontos.trimToSize();
			request.setAttribute("pontos", pontos);
		} catch (Exception ex) {
			saveActionError(request, ex);
		}

		return mapping.findForward("kml");
	}

	public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			
			Long velMinia = 5L;
			Long tempoPArada = 3L; 
			
			SecurityPrincipal user = (SecurityPrincipal) request.getUserPrincipal();
			DynaValidatorForm frm = (DynaValidatorForm) form;
			frm.set("dataFinal", frm.get("dataInicial"));
			
			String veiculoId = frm.getString("veiculoId");						
			
			checkCookie(request, response, frm, "velMinima", velMinia.toString());
			checkCookie(request, response, frm, "tempoParada", tempoPArada.toString());
			
			PeriodoTO periodoTO = new PeriodoTO();
			periodoTO.setDataInicial((String)frm.get("dataInicial"));
			periodoTO.setDataFinal((String)frm.get("dataFinal"));
			periodoTO.setHoraInicial((String)frm.get("horaInicial"));
			periodoTO.setHoraFinal((String)frm.get("horaFinal"));
			
			//Pegar posi��es
			PosicoesService posicoesService =
				(PosicoesService)getBeanSpring(PosicoesService.SERVICE_NAME);
			List<Map<String, String>> pontos =
				posicoesService.consultaPosicoes(veiculoId, periodoTO);
			
			//Pegar paradas
			PontoParadaService paradaService =
				(PontoParadaService)getBeanSpring(PontoParadaService.SERVICE_NAME);
			List<Map<String, String>> paradas =
				paradaService.consultaPontosParadaByVeiculo(veiculoId, 5L, 3L, periodoTO);
			
			Map lastPoint = (Map) pontos.get(pontos.size() - 1);
			String veiculo = user.getDescVeiculo(veiculoId);
			
			request.setAttribute("lastPoint", lastPoint);
			request.setAttribute("veiculo", veiculo);
			request.setAttribute("pontos", pontos);
			request.setAttribute("paradas", ((Map) paradas.get(0)).get("paradas"));
		} catch (Exception ex) {
			saveActionError(request, ex);
		}

		return mapping.findForward("route");
	}
	
	public ActionForward rotaVeiculos(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			DynaValidatorForm frm = (DynaValidatorForm) form;
			frm.set("dataFinal", frm.get("dataInicial"));
			checkCookie(request, response, frm, "velMinima", "5");
			checkCookie(request, response, frm, "tempoParada", "3");				
			
			String rotaId = request.getParameter("rotaId");
			RotaService rotaService = (RotaService)getBeanSpring(RotaService.SERVICE_NAME);
			RotaTO rotaTO = rotaService.buscarRotaById(rotaId);
			
			//Seta as coordenadas atuais dos ve�culos.
			rotaTO.setVeiculos(rotaService.buscarVeiculosDaRotaComCoordenadas(rotaTO));
			
			List<PontoTO> pontos = new ArrayList<PontoTO>();
			pontos.addAll(rotaTO.getPontos());
			
			Collections.sort(pontos, new PontosTOComparator());
			
			//setar pontos da rota no request.
			request.setAttribute("pontos", pontos);			
			request.setAttribute("ulimoPonto", pontos.get(pontos.size()-1));
			
			//setar pontos de fiscaliza��o no request.
			request.setAttribute("pontosFiscalizacao", rotaTO.getPontosFiscalizacao());
			
			//setar veiculos da rota no rquest.
			//request.setAttribute("veiculosRota", rotaTO.getVeiculos());
			
			StringBuffer url = new StringBuffer(request.getRequestURL().toString().replaceAll("/googleearth.do", "/google/reload.jsp"));
			url.append("?horaInicial=" + frm.get("horaInicial"));
			url.append("&horaFinal=23:59:59");
			url.append("&velMaxima=200");
			url.append("&autoCamera=");
			url.append("&showRastro=");
			url.append("&foco=");
			
			url.append("&veiculos=");
			
			boolean flag = true;
			for (VeiculoTO veiculo : rotaTO.getVeiculos()) {
				if (flag) {
					url.append(veiculo.getRealId().toString());
					flag = false;
				} else {
					url.append("," + veiculo.getRealId().toString());
				}
			}
			
			request.setAttribute("URL", url.toString());
			
		} catch (Exception ex) {
			saveActionError(request, ex);
		}

		return mapping.findForward(ROUTE_VEICULOS);
	}
	
	public ActionForward reload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			StringBuffer url = new StringBuffer(request.getRequestURL().toString().replaceAll("/googleearth.do", "/google/reload.jsp"));
			url.append("?horaInicial=" + StringHelper.ifEmpty(request.getParameter("horaInicial")));
			url.append("&horaFinal=" + StringHelper.ifEmpty(request.getParameter("horaFinal")));
			url.append("&velMaxima=" + StringHelper.ifEmpty(request.getParameter("velMaxima")));
			url.append("&autoCamera=" + StringHelper.ifEmpty(request.getParameter("autoCamera")));
			url.append("&showRastro=" + StringHelper.ifEmpty(request.getParameter("showRastro")));
			url.append("&foco=" + StringHelper.ifEmpty(request.getParameter("foco")));
			
			url.append("&veiculos=");
			Enumeration paramNames = request.getParameterNames();
			while (paramNames.hasMoreElements()) {
				String param = (String) paramNames.nextElement();
				if (param.startsWith("veiculoID_") && request.getParameter(param).equals("on")) {
					url.append(param.replaceFirst("veiculoID_", "") + ",");
				}
			}
			url.deleteCharAt(url.length() - 1);
			request.setAttribute("URL", url.toString());
		} catch (Exception ex) {
			saveActionError(request, ex);
		}

		return mapping.findForward("reload");
	}
}
